import {Component, OnInit} from '@angular/core';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {ClassificationService} from '../classification.service';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {Router, NavigationEnd} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {isInteger} from '../../../../../node_modules/@ng-bootstrap/ng-bootstrap/util/util';
import {LocalStorageService} from '../../../lib/service/local-storage.service';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  providers: [ClassificationService]
})
export class ListComponent implements OnInit {
  validateForm: FormGroup;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  isCollapsed = false;
  typeOpen = true;
  sliderWidth = 180;
  total = 0;
  loading = false;
  pageSize = 10;
  page = 1;
  name = '';
  status = '';
  keyword = '';
  checkedIds = [];
  _allChecked = false;
  _indeterminate = false;
  flag = true;
  templateList = [];
  addModalVisible = false;
  submitStatus: boolean;
  shopid: any;
  addSpecNameVisible = false;
  templateId = 0;
  expandDataCache = {};
  modelName = '模板';
  addType: any;
  parentId: any;
  isEdit: boolean;
  template: any;
  opeType: any;
  pid = 0;
  sortType: any;

  constructor(private confirmServ: NzModalService,
              private templateService: ClassificationService,
              private _message: NzMessageService,
              private router: Router,
              private fb: FormBuilder,
              private localStorageService: LocalStorageService,
  ) {
    this.validateForm = fb.group({
      name: ['', [Validators.required, Validators.maxLength(30)]],
      sort: ['', [Validators.required, Validators.min(0), Validators.max(99)], this.integerValidators],
    });
    this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
      this.shopid = this.localStorageService.getShop()['id'];
      this.getTemplateList();
    });
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }

  ngOnInit() {
    // this.shopid = this.localStorageService.getShop()['id'];
    // this.getTemplateList();

  }

  getTemplateList() {
    this.loading = true;
    this.templateService.getTemplateList(this.shopid).subscribe(res => {
      if (res.code === 200) {
        this.templateList = res.data.list;
        this.loading = false;
        // this.templateList.forEach((item, index) => {
        //   if (item.son) {
        //     item.son.forEach((item2, index2) => {
        //       if (item2.son) {
        //         this.templateList[index].son[index2].son = item2.attribute_values;
        //       }
        //       return true;
        //     });
        //   }
        //   return true;
        // });
        console.log('templist', this.templateList);
        this.templateList.forEach(item => {
          this.expandDataCache[item.id] = this.convertTreeToList(item);
        });
      }
    });
  }

  toggleTemplateStatus(id, flag) {
    this.templateService.toggleTemplateStatus(id, flag ? 1 : 0).subscribe(res => {
      if (res.code === 200) {
        this.templateList.forEach((e, i) => {
          if (e.default == 1 && e.id != id) {
            e.default = 0;
          }
        });
        this._message.create('success', '状态修改成功');
        // this.getTemplateList();
      }
    })
  }

  checkedSingele(e, id) {
    if (e) {
      this.checkedIds.push(id);
    } else {
      this.checkedIds.every((val, idx, array) => {
        if (id === val) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
      this.templateList.every((val, idx, array) => {
        if (id === val.id) {
          val.checked = false;
          return false;
        }
        return true;
      })
    }
    this._refreshStatus();
  }


  _checkAll(value) {
    if (value) {
      this.templateList.forEach(item => {
        if (!item.checked) {
          item.checked = true;
          this.checkedIds.push(item.id);
        }
      });
    } else {
      this.templateList.forEach(item => {
        if (item.checked) {
          item.checked = false;
          this.checkedIds.every((val, idx, array) => {
            if (item.id === val) {
              this.checkedIds.splice(idx, 1);
              return false;
            }
            return true;
          });
        }
      });
    }
    this._refreshStatus();
  };

  _refreshStatus() {
    const allChecked = this.templateList.every(value => value.checked === true);
    const allUnChecked = this.templateList.every(value => !value.checked);
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };

  toggleCollapsed(value) {
    this.isCollapsed = value;
    if (!this.isCollapsed) {
      this.typeOpen = true;
    }
  }

  showDeleteConfirm = (id) => {
    let self = this;
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '<b>您确定要删除吗</b>',
      onOk: () => {
        let data = {'id': id, shop_id: this.shopid};
        self.templateService.deleteTemplate(data).subscribe(res => {
          if (res.code === 200) {
            self._message.create('success', '删除成功');
            self.page = 1;
            self.getTemplateList();
          } else {
            self._message.create('error', res.message);
          }
        });
      },
      onCancel() {
      }
    });
  };

  goAddPage() {
    this.addModalVisible = true;
  }

  addSpec(id) {
    this.validateForm.reset();
    this.templateId = id;
    this.isEdit = false;
    this.addModalVisible = true;
  }

  editPage(item, type) {
    this.validateForm.controls['name'].setValue(item.name);
    this.validateForm.controls['sort'].setValue(item.sort);
    if (type === 0) {
      this.pid = 0;
    } else {
      this.pid = item.parent.id;
    }
    this.templateId = item.id;
    this.isEdit = true;
    this.addModalVisible = true;
  }

  sort(e) {
    console.log('e', e);
    if (this.sortType === 'desc') {
      this.sortType = 'asc';
    } else {
      this.sortType = 'desc';
    }
    this.templateService.changeSort({shop_id: this.shopid,  id: 0, type: this.sortType}).subscribe( res =>{
      this.getTemplateList();
    });
  }

  addValue(id) {
    this.templateId = id;
    this.addSpecNameVisible = true;
  }

  closeCouponModal() {
    this.addModalVisible = false;
  }

  // 返回control
  getFormControl(name) {
    return this.validateForm.controls[name];
  }


  _submitForm() {
    console.log('temp', this.templateId);
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    if (this.validateForm.valid) {
      this.submitStatus = true;
      let data = this.validateForm.value;
      data.shop_id = this.localStorageService.getShop()['id'];
      if (this.isEdit) {
        data.url = 'update';
        data.pid = this.pid;
        data.id = this.templateId;

      } else {
        data.url = 'create';
        data.pid = this.templateId;

      }
      console.log('data', data);
      this.templateService.addOrEditTemplateInfo(data).subscribe(res => {
        if (res.code === 200) {
          this._message.create('success', (this.isEdit ? '修改' : '添加') + '成功');
          this.addModalVisible = false;
          this.getTemplateList();
        } else {
          this._message.create('error', res.message);
          this.submitStatus = false;
        }
      });
    }
  }


  collapse(array, data, $event) {
    if ($event === false) {
      if (data.son) {
        data.son.forEach(d => {
          const target = array.find(a => a.id === d.id);
          target.expand = false;
          // this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [], array = [], hashMap = {};
    stack.push({...root, level: 0, expand: false});

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.son) {
        for (let i = node.son.length - 1; i >= 0; i--) {
          stack.push({...node.son[i], level: node.level + 1, expand: false, parent: node});
        }
      }
    }
    console.log('arry', array);
    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }
}
